package com.example.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.base.entity.Chapter;
import com.example.base.entity.Chapter;
import com.example.base.entity.Course;
import com.example.base.mapper.ChapterMapper;
import com.example.base.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ChapterServiceImpl implements ChapterService {

    @Autowired
    ChapterMapper chapterMapper;

    @Override
    public Map<String, Object> selectChapter(Chapter chapter, Integer page, Integer size, String ChapterName) {

        Integer prePage = (page - 1) * size;
        List<Map<String, Object>> list = chapterMapper.selectChapter(chapter, prePage, size, ChapterName);

        for (Map<String, Object> item: list)
        {
                for (String key: item.keySet()){
                    if (key.equals("createTime") || key.equals("updateTime")){
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String createTime = simpleDateFormat.format(item.get(key));
                        item.put(key, createTime);
                    }
                }
        }

        LambdaQueryWrapper<Chapter> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Chapter::getCourseId, chapter.getCourseId());
        Integer total = chapterMapper.selectCount(wrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("records", list);
        map.put("total", total);

        return map;

    }

    @Override
    public Integer addChapter(Chapter Chapter)
    {
        return chapterMapper.insert(Chapter);
    }

    @Override
    public Integer updateChapter(Chapter Chapter) {
        return chapterMapper.updateById(Chapter);
    }

    @Override
    public Integer delChapter(String ChapterId) {
        LambdaUpdateWrapper<Chapter> wrapper = Wrappers.lambdaUpdate();
        // 根据id更新删除标识
        wrapper.eq(Chapter::getChapterId, ChapterId).set(Chapter::getDelSign, 1);
        return chapterMapper.update(null, wrapper);
    }


}
